import type { CompCategory, CompCategoryProps, CompConfig, PermissionConfig } from '@/typings'

const configFiles = import.meta.glob('./*/index.ts', { eager: true })

const configs: Record<string, any[]> = {}
const defaultPropsObj = {} as any
const permissionConfig = {} as Record<string, PermissionConfig>

Object.keys(configFiles).forEach(item => {
  const obj: any = (configFiles[item] as any).default
  const config = { ...obj.config, compTag: `s-${item.match(/\/(\S*)\//)![1]}`, order: obj.order }
  if (!(obj.category in configs)) {
    configs[obj.category] = []
  }
  configs[obj.category].push(config)

  defaultPropsObj[config.compTag] = Object.assign({}, obj.defaultProps)

  permissionConfig[config.compTag] = {
    default: Object.assign(
      { visible: true, modify: true, remove: true }, //默认组件所有操作权限
      obj.permission ? obj.permission.default || {} : {}
    ),
    control: Object.assign(
      { visible: true, modify: true, remove: false }, //删除的控制默认不显示
      obj.permission ? obj.permission.control || {} : {}
    )
  }
})

for (const key in configs) {
  configs[key].sort((pre, next) => {
    return pre.order < next.order ? -1 : 1
  })
  //排序后可删除order
  configs[key].forEach(c => {
    delete c.order
  })
}

const config: Record<CompCategory, Record<CompCategoryProps, string | CompConfig[]>> = {
  basic: {
    name: '基础组件',
    list: configs.basic
  },
  advanced: {
    name: '高级组件',
    list: configs.advanced
  },
  approve: {
    name: '审批组件',
    list: configs.approve
  }
}

const defaultProps = (config: CompConfig) => {
  const common = { col: 24, label: config.label, showLabel: true }
  return { ...common, ...defaultPropsObj[config.compTag] }
}
const getPermissionConfig = (config: CompConfig) => {
  return { ...permissionConfig[config.compTag] }
}

export { config, defaultProps, getPermissionConfig }
